package m.jclecai.com.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import m.jclecai.com.R;
import m.jclecai.com.adapter.ExpandGroupBuyInfoAdapter;
import m.jclecai.com.bean.GroupBuyBean;
import m.jclecai.com.bean.GroupBuyDetailBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.dialog.ShareDialog;
import m.jclecai.com.listener.OnItemClickListener;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.DateUtil;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.BaseBody;
import m.jclecai.com.utils.http.responseBody.GroupPeopleBuyBody;
import m.jclecai.com.view.CustomExpandListview;


/**
 * Created by ZD on 2017/5/15.
 * 合买详情
 */

public class GroupBuyDetailActivity extends LotteryRecordActivity implements OnItemClickListener {

    private ShareDialog mShareDialog;

    @Override
    public int getContentView() {
        return R.layout.activity_group_buy_detail;
    }

    @Override
    public void initView() {
        super.initView();

        rightOptionText("", R.drawable.ic_share_icon);
        tvRightOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mShareDialog == null) {
                    mShareDialog = new ShareDialog(GroupBuyDetailActivity.this);
                }
                mShareDialog.show();
            }
        });

        datas = new ArrayList<>();
        expand_list = (CustomExpandListview) findViewById(R.id.expand_list);
        expand_list.addHeaderView(View.inflate(this, R.layout.header_group_buy_detail, null));
        expand_list.addFooterView(View.inflate(this, R.layout.footer_group_buy_detail, null));
        //覆盖BaseActivity的引用 因为使用了 View.inflate 所以必须等到全部加载了在绑定 能够得到引用
        ButterKnife.bind(this);
        setTitle("合买详情");
        leftOptionText("");
        //总进球
        adapter = new ExpandGroupBuyInfoAdapter(this, expand_list, datas, this);
        expand_list.setAdapter(adapter);
        //悬浮的标题
        expand_list.setHeaderView(getLayoutInflater().inflate(
                R.layout.item_group_buy_parent, expand_list, false));
        expand_list.findViewById(R.id.tv_detail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(GroupBuyDetailActivity.this, OrderDetailActivity.class)
                        .putExtra("id", groupBean.getId()));
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        from = getIntent().getIntExtra("from", 0);
        String str = getIntent().getStringExtra("bean");
        groupBean = FastOk.get(str, GroupBuyBean.class);
        userBean = PreferenceUtil.readUser(this);
        if (ivIcon != null)
            ivIcon.setImageResource(getIcon());
        if (tvSale != null){
            if (null!=groupBean)
            tvSale.setVisibility(groupBean.getTeambuy_left() <= 0 ? View.VISIBLE : View.GONE);
        }
        showActionBottom();
        getData(Constant_Url.GROUP_DETAIL_BUY);
    }

    //根据来源界面不同显示不同的操作按钮
    void showActionBottom() {
        if (flBuy != null)
            flBuy.setVisibility(from == BUY ? View.VISIBLE : View.GONE);
        if (llRecord != null)
            llRecord.setVisibility(from == RECORD ? View.VISIBLE : View.GONE);
    }

    //获取参与用户
    @Override
    protected void getBuyUser() {
        showDialog();
        Map<String, String> pair = new HashMap<>();
        pair.put("user", userBean.getUsername());
        pair.put("password", PreferenceUtil.getPassword(this));
        pair.put("gid", detailBean.getLotteryid());
        pair.put("id", detailBean.getId());
        pair.put("page", String.valueOf(page));
        HttpManager.postAsyn(Constant_Url.GROUP_DETAIL_BUY_PEOPLE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                GroupPeopleBuyBody bean = FastOk.get(response, GroupPeopleBuyBody.class);
                if (bean != null && 0 == bean.getStatus()) {
                    if (datas.size() >= 2)
                        datas.get(1).addAll(bean.getRecords());
                    else
                        datas.add(bean.getRecords());
                    adapter.isShowMore(bean.getPages() != page);
                    page++;
                }
                adapter.notifyDataSetChanged();
            }
        }, pair);
    }

    @Override
    protected void updateText(GroupBuyDetailBean bean) {
        //彩种
        if (tvTitle != null)
            tvTitle.setText(bean.getType());
        //期号
        if (tvNum != null)
            tvNum.setText("第" + bean.getTermNo() + "期");
        long endTime = DateUtil.strToLong(bean.getEndtime());
        //截止时间
        BaseUtils.saleEnd(tvHeadEndTime, endTime, 1000);

        float aa = (groupBean.getTeambuy_left() / 1f / (groupBean.getTeambuy_share() == 0 ? 1 : groupBean.getTeambuy_share()));
        BigDecimal bg = new BigDecimal(aa).setScale(2, RoundingMode.UP);
        int progress = 100 - (int) (bg.floatValue() * 100f);
//        tvProgress.setText(String.valueOf(groupBean.getProgress())+ "%");
        if (tvProgress != null)
            tvProgress.setText((progress + "%"));
        //保%
        if (tvProgressLoss != null)
            tvProgressLoss.setText("保" + groupBean.getProgress_loss() + "%");
        //总金额
        if (tvPrice != null)
            tvPrice.setText((bean.getOne_money() + "元"));
        //我的认购
        if (tvMyPrice != null)
            tvMyPrice.setText((bean.getWin_money() + "元"));
        //发起人
        if (tvName != null)
            tvName.setText(bean.getUsername());
        //中奖纪录
        if (tvRecord != null)
            tvRecord.setText("共" + bean.getWin_money() + "元");//getUser_winmoneys

//        groupStatus.setText(bean.getResult());
        //订单保底
        if (tvEnd != null)
            tvEnd.setText((bean.getTeambuy_loss() + "元"));
        //发单提成
        if (tvCommission != null)
            tvCommission.setText((bean.getTeambuy_commission() + "%"));
        //订单编号
        if (tvOrder != null)
            tvOrder.setText(bean.getPlanNo());
        //方案宣言
        if (tvDesc != null)
            tvDesc.setText(bean.getTeambuy_content());
        //下单时间
        if (tvTime != null)
            tvTime.setText(bean.getAddtime());
        //截止时间
        if (tvFooterEndtime != null)
            tvFooterEndtime.setText(bean.getEndtime());
        //怎么领奖
        if (tvGetGift != null)
            tvGetGift.setText("如中奖，彩金直接返还至购彩账户");
        String teambuy_left = bean.getTeambuy_left();
        if (!TextUtils.isEmpty(teambuy_left))
            surplusLottery = Integer.parseInt(bean.getTeambuy_left());
        if (tvCount != null)
            tvCount.setText("剩" + surplusLottery + "份");
        if (tvSale != null) {
            tvSale.setVisibility(surplusLottery <= 0 ? View.VISIBLE : View.GONE);
            //如果撤单了 不显示购买
            if ("已撤单".equals(bean.getResult())) {
                tvSale.setVisibility(View.VISIBLE);
                tvSale.setText("您购买的方案已撤单");
            } else if (endTime - System.currentTimeMillis() <= 0) {
                tvSale.setVisibility(View.VISIBLE);
                tvSale.setText("方案已截止，下次出手要快点了");
            }
        }
        if (surplusLottery > 0) {
            if (et_count != null)
                et_count.setText("1");
            if (tvPayMoney != null)
                tvPayMoney.setText("1元");
            countBuy = 1;
        }
        if (payAllMoney != null)
            payAllMoney.setText(String.format(getString(R.string.rmb), userBean.getAllmoney()));
    }

    @OnClick(R.id.tv_all_buy)
    void allBuy() {
        if (surplusLottery > 0) {
            if (et_count != null)
                et_count.setText(String.valueOf(surplusLottery));
            if (tvPayMoney != null)
                tvPayMoney.setText((surplusLottery + "元"));
            countBuy = surplusLottery;
        }
    }

    @OnEditorAction(R.id.et_count)
    boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            String s = et_count == null ? "0" : et_count.getText().toString();
            if (TextUtils.isEmpty(s))
                s = "0";
            else if (Integer.valueOf(s) > surplusLottery)
                s = String.valueOf(surplusLottery);
            countBuy = Integer.parseInt(s);
            if (surplusLottery == 0)
                countBuy = 0;
            changeMoney();
        }
        return false;
    }

    @OnClick(R.id.bt_cut)
    void cut() {
        countBuy = countBuy - 1;
        if (countBuy < 1)
            countBuy = 1;
        if (surplusLottery == 0)
            countBuy = 0;
        changeMoney();
    }

    @OnClick(R.id.bt_add)
    void add() {
        countBuy = countBuy + 1;
        if (countBuy > surplusLottery)
            countBuy = surplusLottery;
        changeMoney();
    }

    void changeMoney() {
        if (et_count != null)
            et_count.setText(String.valueOf(countBuy));
        if (tvPayMoney != null)
            tvPayMoney.setText((countBuy + "元"));
    }

    @OnClick(R.id.tv_pay)
    void pay() {
        showAlertDialog("投注确认", "投注金额" + countBuy + "元", "取消", "确认", null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
                Map<String, String> map = new HashMap<>();
                map.put("gid", groupBean.getLotteryid());
                map.put("id", groupBean.getId());
                map.put("part", String.valueOf(countBuy));
                map.put("user", PreferenceUtil.getUserName(GroupBuyDetailActivity.this));
                map.put("password", PreferenceUtil.getPassword(GroupBuyDetailActivity.this));
                HttpManager.postAsyn(Constant_Url.GROUPBUY, new HttpManager.StringCallback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        DisPlay(getString(R.string.error_network));
                        dissDialog();
                    }

                    @Override
                    public void onResponse(String response) {
                        dissDialog();
                        if (!TextUtils.isEmpty(response)) {
                            BaseBody body = FastOk.get(response, BaseBody.class);
                            if (body != null) {
                                DisPlay(body.getMessage());
                                userBean.setAllmoney(String.valueOf(Float.parseFloat(userBean.getAllmoney()) - countBuy));
                                PreferenceUtil.writeUser(GroupBuyDetailActivity.this, userBean);
                                getData(Constant_Url.GROUP_DETAIL_BUY);
                            } else {
                                DisPlay(getString(R.string.error_network));
                            }
                        } else {
                            DisPlay(getString(R.string.error_network));
                        }
                    }
                }, map);
            }
        });
    }

    @Override
    public void onItemClick(int position) {
        getBuyUser();
    }
}
